<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/14
 * Time: 17:39
 */
namespace App\Http\Controllers\Api\V2_0_1;

use App\Http\Requests\Api\V2_0_1\CollectMoneyBillRequest;
use App\Repositories\UserCreditCardRepository;
use App\Services\CollectMoneyService;
use Illuminate\Http\Request;

class CollectMoneyController extends BaseController
{
    protected $collectMoneyService;
    protected $userCreditCardRepository;

    public function __construct(CollectMoneyService $collectMoneyService,
                                UserCreditCardRepository $userCreditCardRepository)
    {
        parent::__construct();
        $this->collectMoneyService = $collectMoneyService;
        $this->userCreditCardRepository = $userCreditCardRepository;
    }

    /**
     * 提现
     */
    public function withdraw(CollectMoneyBillRequest $request)
    {
        $passageId = (int)$request->passage_id;
        //还款通道是否存在
        if (!in_array($passageId, [2, 4])) {
            return $this->responseJson(10703);//收银通道不存在
        }
        //判断是否有绑定
        $creditCard = $this->userCreditCardRepository->validateCreditCardIsUser($request->credit_card_id, $this->user['user_id']);
        if (empty($creditCard->bank_no) || 0 == $creditCard->is_bind) {
            return $this->responseJson(10306);//信用卡不存在
        }
        if (empty($creditCard->expire_date) || empty($creditCard->cvn2)) {
            if (empty($request->expire_date) || empty($request->cvn2)) {
                return $this->responseJson(10517);//信用卡认证
            } else {
                $expireDate = $request->expire_date;
                $cvn2 = $request->cvn2;
                $creditCard->update([
                    'expire_date' => $expireDate,
                    'cvn2' => $cvn2,
                    'update_time' => time()
                ]);
            }
        } else {
            $expireDate = $creditCard->expire_date;
            $cvn2 = $creditCard->cvn2;
        }
        return $this->collectMoneyService->withdraw($passageId, $this->user,
            $request->credit_card_id, $request->bank_card_id, $request->withdraw_money, $expireDate, $cvn2);
    }

    /**
     * 交易记录
     */
    public function tradeRecord(Request $request)
    {
        if (empty($request->credit_card_id)) {
            return $this->responseJson(422);
        }
        return $this->collectMoneyService->tradeRecord($this->user['user_id'], $request->credit_card_id);
    }

    /**
     * 交易明细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function collectMoneyDetail(Request $request)
    {
        $status = json_decode($request->status);
        if (empty($status)) {
            return $this->responseJson(422);
        }
        return $this->collectMoneyService->getDetail($this->user['user_id'], $status, $request->page);
    }
}